package com.hzx.ssm.interceptor;

import com.alibaba.fastjson.JSON;
import com.hzx.ssm.entity.ResBean;
import com.hzx.ssm.util.JWTUtil;
import org.apache.log4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Order(2)
public class UserHandlerInteceptor implements HandlerInterceptor {
    private static final Logger LOG = Logger.getLogger(AdminHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        ResBean resBean = null;
        // 获取请求头中的token验证字符串
        String headerToken = request.getHeader("Usertoken");
        // 检测当前页面，设置当前页不是登录页面时就对其进行拦截
        // 具体方法就是检测URL中有没有login字符串
        if (!request.getRequestURI().contains("/user/login")) {
            if (headerToken == null) {
                // 如果没有token，返回错误信息
                resBean = ResBean.error(401, "未登录，请先登录");
                setReturn(response, resBean);
                return false;
            }
            try {
                // 对token更新与验证
                headerToken = JWTUtil.updateToken(headerToken);
                LOG.debug("token验证通过，并且续期了");
            } catch (Exception e) {
                LOG.debug("token验证出现异常！");
                // 这里的ResponseData类自定义的返回信息类
                resBean = ResBean.error(401, "登陆异常");
                setReturn(response, resBean);
            }
        }
        // 如果有错误信息
        if (resBean != null) {
            setReturn(response, resBean);
            return false;
        } else {
            // 将token加入返回的header中
            LOG.debug("将token加入响应头中");
            response.setHeader("Usertoken", headerToken);
            return true;
        }
    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, ResBean resBean) throws IOException, IOException {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSON(resBean));
        } catch (IOException e) {
            System.out.println("拦截器异常！！！！！！！！！！");
        } finally {
            if (writer != null) {
                writer.close();
            }

        }

    }
}
